//
//  ProductMediaView.swift
//  ptbuy
//
//  Created by MyMac on 2025/1/3.
//

import SwiftUI
import AVFoundation
import AVKit
import CoreData
struct ProductMediaView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @Binding var mediaStatus:Bool
    @Binding var productId:String
    @Binding var mediaStatusSuccess:Bool
    
    @State private var permissionStatus: AVAuthorizationStatus = .notDetermined
    //调用相机拍照
    @State private var isImagePickerPresented = false
    //调用相机录像
    @State private var isCameraPresented = false
    @State private var permissAlert = false  // 控制是否显示Alert
    @State private var photo:Int8 = 0//记录已有照片数
    @State private var video:Int8 = 0//记录已有视频数
    @State private var medias:[String] = [] // 图片数组，替换成你的图片名称
    @State private var type:Int8 = 0//类型；0:拍照;1:选择相册
    @State private var selectedImageIndex = 0 // 当前选中的图片索引
    @State private var isDeleteAlert = false // 当前选中的图片索引
    @State private var isDeleteVideoAlert = false // 当前选中的视频索引
    @State private var isImagePresented = false//点击图片全屏显示
    @State private var isFullScreen = false//点击视频全屏显示
    
//    @State private var product:Product
    
   
    
    var body: some View {
        NavigationView{
            VStack{
                Divider()
                HStack{
                    Button(action:{
                        permissionStatus = AVCaptureDevice
                            .authorizationStatus(for: .video)
                        type=0
                        if permissionStatus == .authorized {
                            isImagePickerPresented = true
                        }else if permissionStatus == .denied {
                            permissAlert = true
                        } else {
                            requestCameraPermission()
                        }
                                            
                    }){
                        Text("拍照").frame(width:50,height:8).foregroundColor(.black)
                    }.alert(isPresented: $permissAlert){
                        Alert(
                            title: Text("提示"),
                            message: Text(
                                "相机权限已被拒绝，请前往设置中开启权限"
                            ),
                            primaryButton: .destructive(Text("前往设置")) {
                                permissAlert = false
                                if let settingsURL = URL(
                                    string: UIApplication.openSettingsURLString
                                ) {
                                    UIApplication.shared.open(settingsURL)
                                }
                            },
                            secondaryButton: .cancel(Text("关闭")) {
                                permissAlert = false
                            })
                    }.sheet(isPresented: $isImagePickerPresented) {
                        ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                    medias:$medias,
                                    type:$type,
                                    photo:$photo)
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color("btn")).opacity(0.8)
                        .cornerRadius(8)
                    Spacer()
                    Button(action:{
                        isCameraPresented = true
                    }){
                        Text("录像").frame(width:50,height:8).foregroundColor(.black)
                    }.sheet(isPresented: $isCameraPresented) {
                        VideoPicker(
                            isPresented: $isCameraPresented,
                            medias:$medias,
                            video:$video
                        )
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color("btn")).opacity(0.8)
                        .cornerRadius(8)
                    Spacer()
                    
                    Button(action:{
                        type=1
                        isImagePickerPresented = true
                    }){
                        Text("相册").frame(width:50,height:8).foregroundColor(.black)
                    }.sheet(isPresented: $isImagePickerPresented) {
                        ImagePicker(isImagePickerPresented: $isImagePickerPresented,
                                    medias:$medias,
                                    type:$type,
                                    photo:$photo)
                    }.padding()
                        .foregroundColor(.black)
                        .background(Color("btn")).opacity(0.8)
                        .cornerRadius(8)
                    Spacer()
                }.padding()
                Text("已有：照片：\(photo)张；视频：\(video)个")
                    .multilineTextAlignment(.leading)
                    .padding(.horizontal, 10)
                TabView (selection: $selectedImageIndex){

                    ForEach(0..<medias.count, id: \.self) { index in
                        if(
                            medias[index]
                                .contains(".mov") ||  medias[index]
                                .contains(".MOV")
                        ){
                            VStack{
                                HStack{
                                    Text("")
                                    Spacer()
                                    Image("shanchu") // 这里不需要加文件扩展名
                                        .resizable()   // 使图片可调整大小
                                        .scaledToFit() // 保持图片比例
                                        .frame(width: 25, height: 25) // 设置图片的尺寸
                                        .padding([.top,.trailing],8)
                                        .onTapGesture(){
                                            isDeleteVideoAlert = true
                                        }.alert(
                                            "确定删除此视频吗？",
                                            isPresented:$isDeleteVideoAlert
                                        ){
                                            Button("关闭", role: .cancel) {
                                                isDeleteVideoAlert = false
                                            }
                                            Button("删除", role: .destructive) {
                                                
                                                medias.remove(at: selectedImageIndex)
                                                    video -= 1
                                                isDeleteVideoAlert = false
                                            }
                                        }
                                }
                                let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                    medias[index]
                                )
                                
                                let player = AVPlayer(
                                    url: URL(fileURLWithPath: filename.path)
                                );
                                VideoPlayer(player: player)
                                    .onTapGesture {
                                        // 点击时，进入全屏模式
                                        isFullScreen = true
                                    }.onAppear {
                                        // 在视图显示时播放视频
                                        player.pause()
                                    }.fullScreenCover(
                                        isPresented:$isFullScreen
                                    ){
                                        let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                            medias[selectedImageIndex]
                                        )
                    
                                        let player = AVPlayer(
                                            url: URL(
                                                fileURLWithPath: filename.path
                                            )
                                        );
                                        // 全屏播放视频
                                        VideoPlayer(player: player)
                                            .edgesIgnoringSafeArea(
                                                .all
                                            ) // 使视频全屏
                                            .onTapGesture() {
                                                // 点击时，进入全屏模式
                                                isFullScreen = false
                                                player.pause()
                                            }.onAppear {
                                                // 在视图显示时播放视频
                                                player.play()
                                            }
                                    }

                            }
                        }else{
                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                medias[index]
                            )
                            if let uiImage = UIImage(
                                contentsOfFile: filename.path
                            ) {
                                
                                VStack{
                                    HStack{
                                        Text("")
                                        Spacer()
                                        Image("shanchu") // 这里不需要加文件扩展名
                                            .resizable()   // 使图片可调整大小
                                            .scaledToFit() // 保持图片比例
                                            .frame(
                                                width: 25,
                                                height: 25
                                            ) // 设置图片的尺寸
                                            .padding([.top,.trailing],8)
                                            .onTapGesture(){
                                                isDeleteAlert = true
                                            }.alert(
                                                "确定删除此照片吗？",
                                                isPresented:$isDeleteAlert
                                            ){
                                                Button("关闭", role: .cancel) {
                                                    isDeleteAlert = false
                                                }
                                                Button( "删除",role: .destructive ) {
                                                    medias.remove(at: selectedImageIndex)
                                                        photo -= 1
                                                    isDeleteAlert = false
                                                }
                                            }
                                    }
                                   
                                    
                                    // 从文件路径加载图片
                                    Image(uiImage: uiImage)
                                        .resizable()  // 使图片可调整大小
                                        .scaledToFit()  // 保持比例缩放
                                        .frame(
                                            width: UIScreen.main.bounds.width,
                                            height: 300
                                        )
                                    // 设置显示尺寸
                                        .padding()
                                        .onTapGesture {
                                            // 点击图片时，显示大图
                                            isImagePresented = true
                                        }.fullScreenCover(
                                            isPresented: $isImagePresented
                                        ) {
                                            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                                                medias[selectedImageIndex]
                                            )
                                            if let uiImage = UIImage(
                                                contentsOfFile: filename.path
                                            ) {
                                                // 显示大图的视图
                                                Image(
                                                    uiImage: uiImage
                                                ) // 用你的图片名称替换
                                                .resizable()
                                                .scaledToFit()
                                                .edgesIgnoringSafeArea(.all)
                                                .onTapGesture {
                                                    // 点击大图时关闭
                                                    isImagePresented.toggle()
                                                }
                                            }
                                          
                                        }
                                }
                                
                                

                            } else {
                                Text("File not found")
                                    .foregroundColor(.red)
                            }
                        }
                       
                    }
                }.tabViewStyle(
                    PageTabViewStyle(indexDisplayMode: .always)
                )// 启用分页样式
                .frame(height: 350) // 设定图片视图的高度
                .background(Color(.white))
                .padding()
               
                
                
                Spacer()
            }.onAppear{
                fetchPriduct()
            }.frame(maxWidth:.infinity,maxHeight: .infinity).background(
                // 创建渐变背景
                LinearGradient(
                    gradient: Gradient(
                        colors: [
                            Color("startColor").opacity(
                                10
                            ),
                            // 上半部分颜色，增加不透明度
                            Color("endColor")
                        ]// 上半部分颜色，增加不透明度
                    ),
                    startPoint: .top,
                    endPoint: .bottom
                )
                .edgesIgnoringSafeArea(.all)  // 确保背景覆盖整个屏幕
            ).navigationBarTitle("修改照片信息", displayMode: .inline).navigationViewStyle(
                StackNavigationViewStyle()
            ) // 推荐在全屏时使用此样式
            .background(
                // 背景遮罩
                Color.black.opacity(0.5)
                    .edgesIgnoringSafeArea(.all)
                
            )
            .toolbar {
                // 修改标题字体大小
                ToolbarItem(placement: .topBarLeading) {
                    Text("返回")
                        .clipShape(
                            Capsule()
                        ) // 使用 Capsule 形状来实现圆角效果
                        .onTapGesture {
                            mediaStatus = false
                        }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Text("保存")
                        .clipShape(
                            Capsule()
                        ) // 使用 Capsule 形状来实现圆角效果
                        .onTapGesture {
                            modifyProduct()
                        }
                }
            }
        }
    }
    
    
    /*
     修改商品信息
     */
    private func modifyProduct(){
        // 查找对应的 Product
        let fetchRequest: NSFetchRequest<Product> = Product.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "id == %@", productId)
        
        do {
            let results = try viewContext.fetch(fetchRequest)

            if let product = results.first {
                // 更新该 person 的名字
                if !medias.isEmpty{
                    product.mult = Utils.convertArrayToJsonString(stringArray: medias)
                }else{
                    product.mult = nil
                }
                try viewContext.save()  // 保存更新
                mediaStatus = false
            }
        } catch {
            mediaStatus = false
            mediaStatusSuccess = true
            print("更新失败：\(error.localizedDescription)")
        }
    }
    
    
    /*
     手动查询
     */
    func fetchPriduct(){
        let fetchRequest: NSFetchRequest<Product> = Product.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Product.myorder, ascending: false)]
        fetchRequest.predicate = NSPredicate(format: "id = %@",productId)
       do {
           let results  = try viewContext.fetch(fetchRequest) // 执行查询并获取数据
           if let myProduct = results.first {
               if let mult = myProduct.mult,!mult.isEmpty{
                   let strAndJson:[String] = Utils.convertJsonStringToArray(
                       jsonString: mult
                   )
                   if strAndJson.count>0{
                       for str in strAndJson{
                           medias.append(str)
                           if(str.contains(".mov") || str.contains(".MOV")){
                               video += 1
                           }else{
                               photo += 1
                           }
                       }
                   }
               }
           }
       } catch {
           print("Failed to fetch items: \(error)")
       }
    }
    
    func requestCameraPermission() {
        AVCaptureDevice.requestAccess(for: .video) { response in
            DispatchQueue.main.async {
                permissionStatus = AVCaptureDevice
                    .authorizationStatus(for: .video)
            }
        }
    }
}


